package com.meta.context.source.http.util;

/**
 * @Author fuzhilin
 * @Description //TODO
 * @Date 2023/12/4 14:02
 **/

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy;
import org.apache.hc.client5.http.impl.DefaultHttpRequestRetryStrategy;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class HttpUtils {
    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 100000;

    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 100000;


    private static final int MAX_TIMEOUT = 100000;
    private static final CloseableHttpClient httpClient;

    static {
        // 自定义 SSL 策略
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", createSSLConnSocketFactory())
                .build();
        // 设置连接池
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(registry);
        connMgr.setMaxTotal(100); // 设置连接池大小
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); // 设置每条路由的最大并发连接数
        connMgr.setValidateAfterInactivity(TimeValue.ofSeconds(600)); // 设置长连接

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(Timeout.ofMilliseconds(MAX_TIMEOUT))                   // 建立连接超时时间
                .setResponseTimeout(Timeout.ofSeconds(MAX_TIMEOUT))                    // 传输超时
                .setConnectionRequestTimeout(Timeout.ofMilliseconds(MAX_TIMEOUT))         // 设置从连接池获取连接实例的超时
                .build();

        httpClient = HttpClients.custom()
                .setConnectionManager(connMgr)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRetryStrategy(new DefaultHttpRequestRetryStrategy())  // 重试 1 次，间隔1s
                .setDefaultRequestConfig(requestConfig).setConnectionManagerShared(true)
                .build();
    }
    /**
     * 发送get请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Integer connectTimeout, Integer socketTimeout) throws Exception {
        return doGet(url, connectTimeout, socketTimeout);
    }

    /**
     * 发送get请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, CONNECT_TIMEOUT, SOCKET_TIMEOUT);
    }

    /**
     * 发送get请求；带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        return doGet(url, null, params, connectTimeout, socketTimeout);
    }

    /**
     * 发送get请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        // 创建httpClient对象
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        if (ObjectUtil.isNull(connectTimeout)) {
            connectTimeout = CONNECT_TIMEOUT;
        }
        if (ObjectUtil.isNull(socketTimeout)) {
            socketTimeout = SOCKET_TIMEOUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout, TimeUnit.MICROSECONDS).setResponseTimeout(connectTimeout,TimeUnit.MICROSECONDS).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 释放资源
            release(httpResponse,httpClient);
        }
    }

    /**
     * 发送post请求；不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Integer connectTimeout, Integer socketTimeout) throws Exception {
        return doPost(url, connectTimeout, socketTimeout);
    }

    /**
     * 发送post请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        return doPost(url, null, params, connectTimeout, socketTimeout);
    }

    /**
     * 发送post请求；带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        // 创建httpClient对象
        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        if (ObjectUtil.isNull(connectTimeout)) {
            connectTimeout = CONNECT_TIMEOUT;
        }
        if (ObjectUtil.isNull(socketTimeout)) {
            socketTimeout = SOCKET_TIMEOUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setResponseTimeout(connectTimeout,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(socketTimeout,TimeUnit.MICROSECONDS).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        httpPost.setHeader("Accept", "application/json");

        packageHeader(headers, httpPost);

        // 封装请求参数
        packageParam(params, httpPost);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    public static HttpClientResult doPostJson(String url, Map<String, String> headers, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
         * 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        if (ObjectUtil.isNull(connectTimeout)) {
            connectTimeout = CONNECT_TIMEOUT;
        }
        if (ObjectUtil.isNull(socketTimeout)) {
            socketTimeout = SOCKET_TIMEOUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(connectTimeout,TimeUnit.MICROSECONDS).setResponseTimeout(socketTimeout,TimeUnit.MICROSECONDS).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        //httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

        packageHeader(headers, httpPost);

        // 封装请求参数
        //packageParam(params, httpPost);
        StringEntity s = new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON,"UTF-8",false);
        httpPost.setEntity(s);
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse,httpClient);
        }
    }

    /**
     * 使用httpclint 发送文件
     *
     * @param url 调用的连接
     *            parms 使用map装入需要调用的参数名与值
     * @return 响应结果
     * @author: weibaoting
     * @date: 2023-01-06
     */
    public static HttpClientResult doPostForm(String url, Map<String, String> headers, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        if (ObjectUtil.isNull(connectTimeout)) {
            connectTimeout = CONNECT_TIMEOUT;
        }
        if (ObjectUtil.isNull(socketTimeout)) {
            socketTimeout = SOCKET_TIMEOUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(connectTimeout,TimeUnit.MICROSECONDS).setResponseTimeout(socketTimeout,TimeUnit.MICROSECONDS).build();
        httpPost.setConfig(requestConfig);
        packageHeader(headers, httpPost);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        params.forEach((key, value) -> list.add(new BasicNameValuePair(key, String.valueOf(value))));
        if (Objects.nonNull(params) && params.size() > 0) {
            httpPost.setEntity(new UrlEncodedFormEntity(list, StandardCharsets.UTF_8));
        }
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;
        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送put请求；不带请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * 发送put请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url, Map<String, String> headers, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        HttpPut httpPut = new HttpPut(url);
        if (ObjectUtil.isNull(connectTimeout)) {
            connectTimeout = CONNECT_TIMEOUT;
        }
        if (ObjectUtil.isNull(socketTimeout)) {
            socketTimeout = SOCKET_TIMEOUT;
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(connectTimeout,TimeUnit.MICROSECONDS).setResponseTimeout(socketTimeout,TimeUnit.MICROSECONDS).build();
        httpPut.setConfig(requestConfig);
        packageHeader(headers, httpPut);
        packageParam(params, httpPut);

        CloseableHttpResponse httpResponse = null;

        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }
    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params headers
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPutJson(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        //HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setResponseTimeout(SOCKET_TIMEOUT,TimeUnit.MICROSECONDS).build();
        HttpPut httpPut=new HttpPut(url);
        httpPut.setConfig(requestConfig);
        // 封装头部参数
        headers.put("Content-Type", "application/json;charset=utf-8");
        packageHeader(headers, httpPut);
        // 封装请求参数
        StringEntity s = new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON,"UTF-8",false);
        httpPut.setEntity(s);
        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }
    /**
     * 发送delete请求；不带请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url) throws Exception {
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setResponseTimeout(SOCKET_TIMEOUT,TimeUnit.MICROSECONDS).build();
        httpDelete.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url, Map<String, Object> params, Integer connectTimeout, Integer socketTimeout) throws Exception {
        if (params == null) {
            params = new HashMap<String, Object>();
        }

        params.put("_method", "delete");
        return doPost(url, params, connectTimeout, socketTimeout);
    }

    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params headers
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setResponseTimeout(SOCKET_TIMEOUT,TimeUnit.MICROSECONDS).build();
        httpDelete.setConfig(requestConfig);
        // 封装头部参数
        packageHeader(headers, httpDelete);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 发送delete请求；带请求参数
     *
     * @param url    请求地址
     * @param params headers
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDeleteJson(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        //HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setConnectionRequestTimeout(CONNECT_TIMEOUT,TimeUnit.MICROSECONDS).setResponseTimeout(SOCKET_TIMEOUT,TimeUnit.MICROSECONDS).build();
        HttpDelete httpDelete=new HttpDelete(url);
        httpDelete.setConfig(requestConfig);
        // 封装头部参数
        headers.put("Content-Type", "application/json;charset=utf-8");
        packageHeader(headers, httpDelete);
        // 封装请求参数
        StringEntity s = new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON,"UTF-8",false);
        httpDelete.setEntity(s);
        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpUriRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, Object> params, HttpUriRequestBase httpMethod) throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, Charset.forName(ENCODING)));
        }
    }

    /**
     * Description: 获得响应结果
     *
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpUriRequestBase httpMethod) throws Exception {
        // 执行请求
        httpResponse = httpClient.execute(httpMethod);

        // 获取返回结果
        if (httpResponse != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return new HttpClientResult(httpResponse.getCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;    // 信任所有证书
                }
            });
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
        return sslsf;
    }
}